package pub.tbc.mybatis.extend.type;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.joda.time.DateTime;

import java.sql.*;
import java.time.Instant;
import java.util.StringJoiner;

/**
 * @author tbc on 2017/5/8 11:14:22.
 */
@Slf4j
@MappedJdbcTypes(JdbcType.TIMESTAMP)
@MappedTypes(String.class)
public class DateTimeTypeHandler extends BaseTypeHandler<String> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setTimestamp(i, Timestamp.valueOf(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnName);
        if (sqlTimestamp != null) {
            return new DateTime(sqlTimestamp.getTime()).toString("yyyy-MM-dd HH:mm:ss");
        }
        return null;
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = rs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return new DateTime(sqlTimestamp.getTime()).toString("yyyy-MM-dd HH:mm:ss");
        }
        return null;
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        Timestamp sqlTimestamp = cs.getTimestamp(columnIndex);
        if (sqlTimestamp != null) {
            return new DateTime(sqlTimestamp.getTime()).toString("yyyy-MM-dd HH:mm:ss");
        }
        return null;
    }

    public static void main(String[] args) {
        StringJoiner joiner = new StringJoiner(",");
        System.out.println(joiner.add("a").add("b").toString());

        System.out.println(Timestamp.from(Instant.now()));
    }

}
